//
//  Hear_AddNewTopicViewController.m
//  Hear
//
//  Created by mac on 2018/4/29.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "Hear_AddNewTopicViewController.h"

#import "EaseChatToolbar.h"

#import "HRRecordAudioViewModel.h"

#import "Hear_EditVoiceViewController.h"

#import "OSSImageUploader.h"

@interface Hear_AddNewTopicViewController () {
    NSTimer *myTimer;
    NSInteger timeCount;
    int number;
    BOOL play;
}

@property(nonatomic, strong) UIView *topView;

/** 问题TV */
@property (nonatomic, strong) Hear_CustomTextView *questionTV;

/** 录制时间 */
@property (nonatomic, strong) UILabel *timeLabel;

@property (nonatomic, strong) UIImageView *showImageView;

@property (nonatomic, strong) UILabel *show;

@property(nonatomic, strong) EaseChatToolbar *chatToolbar;

@property(nonatomic, strong) UIButton *playButton;

@property(nonatomic, strong) HRRecordAudioViewModel *audioViewModel;

@end

@implementation Hear_AddNewTopicViewController

- (HRRecordAudioViewModel *)audioViewModel {
    if (_audioViewModel == nil) {
        _audioViewModel = [[HRRecordAudioViewModel alloc] init];
        WeakSelf
        _audioViewModel.addEnditBlock = ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.playButton.selected = YES;
            });
        };
    }
    return _audioViewModel;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [myTimer invalidate];
    myTimer = nil;
    
    [self.audioViewModel.audioPlayer stop];
    [self.chatToolbar.waterWaveView stopAnimation];
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]){
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self setupUI];
    
    // 检查录制权限
    [self.audioViewModel checkRecord];
}

- (void)setupUI {
    self.title = @"留声机话题";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *nextbtn = [[UIButton alloc]init];
    nextbtn.size = CGSizeMake(60 * scaleWidth, 25 * scaleHeight);
    [nextbtn setTitle:@"下一步" forState:UIControlStateNormal];
    nextbtn.titleLabel.font = CustomUIFont(14);
    [nextbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextbtn addTarget:self action:@selector(nextbtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:nextbtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, kTopHeight, kFullWidth, 170)];
    [self.view addSubview:self.topView];
    
    Hear_CustomTextView *questionTV = [[Hear_CustomTextView alloc] initWithFrame:CGRectMake(10, 5, self.topView.width-20, 150)];
    questionTV.placeholder = self.placeholder;
    questionTV.font = [UIFont systemFontOfSize:15];
    questionTV.textAlignment = NSTextAlignmentLeft;
    questionTV.layer.cornerRadius = 5;
    questionTV.layer.masksToBounds = YES;
    questionTV.layer.borderWidth = 1;
    questionTV.layer.borderColor = [UIColor colorWithHexString:@"#f1f1f1"].CGColor;
    self.questionTV = questionTV;
    [self.topView addSubview:questionTV];
    
    UILabel *bottomView = [[UILabel alloc] initWithFrame:CGRectMake(0, questionTV.bottom + 5, self.topView.width, self.topView.height-questionTV.bottom)];
    [self.topView addSubview:bottomView];
    bottomView.backgroundColor = CustomColor(240, 240, 240, 1);
    
    UIImageView *showImageView = [UIImageView new];
    showImageView.image = [UIImage imageNamed:@"生成名片圆环"];
    showImageView.frame = CGRectMake((kFullWidth-180)/2, self.topView.bottom+50, 180, 180);
    showImageView.userInteractionEnabled = YES;
    self.showImageView = showImageView;
    [self.view addSubview:showImageView];
    
    UILabel *timeLabel = [UILabel new];
    timeLabel.font = CustomUIFont(19);
    timeLabel.textColor =FirstTextColor;
    [self.view addSubview:(self.timeLabel=timeLabel)];
    timeLabel.textAlignment = 1;
    timeLabel.frame = CGRectMake((kFullWidth-80)/2, showImageView.top, 80, 40);
    timeLabel.text = @"0S";
    [self.timeLabel addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    UIButton *playButton = [UIButton buttonWithType:0];
    [playButton addTarget:self action:@selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [playButton setImage:[UIImage imageNamed:@"hear_play"] forState:0];
    [playButton setImage:[UIImage imageNamed:@"hear_pase"] forState:UIControlStateSelected];
    [showImageView addSubview:(self.playButton=playButton)];
    playButton.frame = CGRectMake((showImageView.width-45)/2, (showImageView.height-45)/2, 45, 45);
    
    UILabel *show = [UILabel new];
    show.text = @"可录制5S-120S";
    show.font = [UIFont systemFontOfSize:15];
    show.textColor = FirstTextColor;
    self.show = show;
    [self.view addSubview:show];
    
    [show mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(showImageView);
        make.top.mas_equalTo(showImageView.mas_bottom).mas_offset(10 * scaleHeight);
    }];
    
    WeakSelf
    CGFloat chatbarHeight = [EaseChatToolbar defaultHeight];
    self.chatToolbar = [[EaseChatToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - chatbarHeight, self.view.frame.size.width, chatbarHeight) type:HRChatToolbarTypeRecord];
    [self.view addSubview:self.chatToolbar];
    
    self.chatToolbar.finishRecord = ^{
        
        timeCount = 0;
        [weakSelf.audioViewModel stopRecord];
        [myTimer invalidate];
        myTimer = nil;
        
    };
    
    // 开始录音
    self.chatToolbar.starRecordingBlock = ^{
        
        // 开始录制
        myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
        play = YES;
        
        // 显示录音秒数
        [weakSelf.audioViewModel recorlAudio];
        
        weakSelf.chatToolbar.waterWaveView.recorder = weakSelf.audioViewModel.audioRecorder;
        
    };
    
    // 停止录音
    self.chatToolbar.stopRecordingBlock = ^() {
        
        NSString *tempstr = [self.timeLabel.text stringByReplacingOccurrencesOfString:@"S" withString:@""];
        weakSelf.chatToolbar.videotime = [tempstr intValue];
        weakSelf.chatToolbar.videoenter = @"1";
        
        // 结束录制
        [weakSelf.audioViewModel recorlAudio];
        
        [myTimer invalidate];
        myTimer = nil;
        
    };
    
    // 播放语音
    self.audioViewModel.audioPlayerDidFinishPlaying = ^{
        [self playButtonClick:playButton];
    };
    
    UIButton *showRecordButton = [UIButton buttonWithType:0];
    [showRecordButton setImage:[UIImage imageNamed:@"录制_语音"] forState:0];
    [showRecordButton setTitle:@" 自己先表达/回答后,才能发布(点击录制)" forState:0];
    showRecordButton.frame = CGRectMake(10, self.topView.bottom+10 * scaleHeight, 230 * scaleWidth, 20 * scaleHeight);
    [showRecordButton setTitleColor:BlueColor forState:0];
    showRecordButton.titleLabel.font = CustomUIFont(13);
    [showRecordButton addTarget:self action:@selector(showRecordButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:showRecordButton];

    showImageView.hidden = YES;
    timeLabel.hidden = YES;
    playButton.hidden = YES;
    show.hidden = YES;
    self.chatToolbar.hidden = YES;
    
}

- (void)showRecordButtonClick{
    self.showImageView.hidden = NO;
    self.timeLabel.hidden = NO;
    self.playButton.hidden = NO;
    self.chatToolbar.hidden = NO;
    self.show.hidden = NO;
}

- (void)timeChange{
    timeCount ++;
    self.timeLabel.text = [NSString stringWithFormat:@"%dS",timeCount];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([object isEqual:self.timeLabel]) {
        NSString *newStr = [change objectForKey:NSKeyValueChangeNewKey];
        
        NSString *tempstr = [newStr stringByReplacingOccurrencesOfString:@"S" withString:@""];
        
        if ([tempstr intValue] == 110) {
            [self showMessage:@"您至多可录制120S" atPosition:ShowPosition_Center];
        }
        if ([tempstr intValue] == 120) {
            
            // 结束录制
            [self.audioViewModel recorlAudio];
            
            [myTimer invalidate];
            myTimer = nil;
            
            [self showMessage:@"您已经录制满120S" atPosition:ShowPosition_Center];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ReportTimeLength" object:nil];
            
        }
        
    }
}

- (void)playButtonClick:(UIButton *)button{
    
    if (!self.audioViewModel.mp3Path.length){
        [self showMessage:@"请先录制音频" atPosition:ShowPosition_Center];
        return;
    }
    
    button.selected = !button.isSelected;
    
    if (button.isSelected){
        [self.audioViewModel playRecordingWithPath:self.audioViewModel.mp3Path];
    } else {
        [self.audioViewModel.audioPlayer pause];
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:NO];
}

#pragma mark 下一步
- (void)nextbtnAction:(UIButton *)sender {
    
    if (!self.questionTV.text.length){
        [self showMessage:@"请输入您要创建的话题" atPosition:ShowPosition_Center];
        return ;
    }
    
    if (!self.audioViewModel.outPutFilePath.length) {
        [self showMessage:@"请先回答您创建的话题" atPosition:ShowPosition_Center];
        return ;
    }
    
    NSScanner *scanner = [NSScanner scannerWithString:self.timeLabel.text];
    [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
    [scanner scanInt:&number];
    
    Hear_EditVoiceViewController *vc = [Hear_EditVoiceViewController new];
    vc.fromVC = @"add";
    vc.topicName = self.questionTV.text;
    vc.soundPath = self.audioViewModel.outPutFilePath;
    NSString *tempstr = [self.timeLabel.text stringByReplacingOccurrencesOfString:@"S" withString:@""];
    vc.audioLength = [tempstr floatValue];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)dealloc {
    [myTimer invalidate];
    myTimer = nil;
    
    [self.timeLabel removeObserver:self forKeyPath:@"text"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
